import CardTitle from '@/components/CardTitle';
import { rankModule } from '@/services/api/api-monitor-business';
import { Bar, Pie } from '@ant-design/charts';
import ProCard from '@ant-design/pro-card';
import { Avatar, Card, Col, DatePicker, List, Progress, Row } from 'antd';
import moment from 'moment';
import { useEffect, useState } from 'react';
const RankModule: React.FC = ({ }) => {
  const monthFormat = 'YYYY-MM';

  const startOfYear = moment().startOf('year');
  const endOffYear = moment().endOf('year');
  const rankIcon = [
    '/image/排行榜第一名（56X56）.png',
    '/image/排行榜第二名（56X56）.png',
    '/image/排行榜第三名（56X56）.png',
  ];
  /**
   * 市级部门
   */
  const [data, setDataState] = useState<any[]>([]);
  const [tab, setTab] = useState('选题计划');

  useEffect(() => {
    loadData([moment(startOfYear).format('YYYY-MM'), moment(endOffYear).format('YYYY-MM')]);
  }, []);

  /**
   * 排行榜
   */
  const loadData = async (createdTimes: any) => {
    try {
      const response = await rankModule({ createdTimes });
      if (response.code === 0) {
        setDataState(response.data);
      }
    } catch (error) { }
  };
  const getMaxCount = (i) => {
    const maxCount = data[i].data.reduce((max, item) => {
      return item.count > max ? item.count : max;
    }, 0);
    return maxCount
  }
  const renderRank = (item: BulletinData.PageResult, index, title) => {
    let maxSend
    let maxPublish
    if (data.length > 2) {
      maxSend = getMaxCount(1)
      maxPublish = getMaxCount(2)
    } else {
      maxPublish = getMaxCount(1)
    }
    return (
      <>
        <Card key={item.id} style={{
          width: '100%',
          borderRadius: '0',
          boxShadow: 'none',
          padding: '4px'
        }} bordered={false}>
          <Card.Meta
            avatar={
              <>
                {index <= 2 ? <Avatar size={'default'} src={rankIcon[index]}></Avatar> : <div
                  style={{
                    backgroundColor: '#5083E1',
                    borderRadius: '50%',
                    width: '23px',
                    height: '23px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    marginLeft: '5px',
                    marginTop: '5px',
                    color: 'white',
                  }}
                >
                  {index + 1}
                </div>
                }
              </>
            }
            title={
              <>
                <div
                  style={{
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    marginTop: '5px',
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'flex-start',
                    height: '23px'
                  }}
                >
                  <div style={{ width: '20%' }}>{item.org.length > 6
                    ? item.org.slice(0, 6) + '...'
                    : item.org}</div>
                  <div style={{ width: '60%' }}>
                    {title === "主动报送" && (
                      <Progress
                        percent={Math.round((item.count / maxSend) * 100)}
                        format={(percent) => `${percent}`}
                        style={{ marginLeft: '30px' }}
                        strokeWidth={13}
                      />
                    )}
                    {title === "选题刊播" && (
                      <Progress
                        percent={Math.round((item.count / maxPublish) * 100)}
                        format={(percent) => `${percent}`}
                        style={{ marginLeft: '30px' }}
                        strokeWidth={13}
                      />
                    )}

                  </div>
                </div>
              </>
            }
          />
        </Card>
      </>
    );
  };
  return (
    <>
      <ProCard
        title={<CardTitle>排行榜</CardTitle>}
        gutter={[60, 60]}
        wrap
        extra={
          <DatePicker.RangePicker
            picker="month"
            allowClear={false}
            defaultValue={[startOfYear, endOffYear]}
            format={monthFormat}
            onChange={(date, dateString) => {
              loadData(date);
            }}
          />
        }
        bodyStyle={{
          margin: 0,
        }}
        tabs={{
          activeKey: tab,
          onChange: (key) => {
            setTab(key);
          },
        }}
      >
        {data &&
          data.map((item, index) => (
            <ProCard.TabPane key={item?.title} tab={item?.title}>
              {index === 0 ? (<>

                <ProCard
                  // title={item.title}
                  size="small"
                  colSpan={{ xs: 24, sm: 8, md: 8, lg: 8, xl: 8 }}
                >
                  <Pie
                    style={{
                      height: '30vh',
                      width: '20vw',
                      marginLeft:'100px'
                    }}
                    {...{
                      appendPadding: 10,
                      data: item.data,
                      angleField: 'count',
                      colorField: 'org',
                      radius: 1,
                      innerRadius: 0.64,
                      label: {
                        type: 'inner',
                        offset: '-50%',
                        style: {
                          textAlign: 'center',
                        },
                        autoRotate: false,
                        content: '{value}',
                      },
                      statistic: {
                        title: false,
                        content: {
                          style: {
                            whiteSpace: 'pre-wrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                          },
                          content: '',
                        },
                      },
                    }}
                  />
                </ProCard>

              </>) : (<>
                <ProCard
                  style={{ marginTop: 8 }}
                  colSpan={{ xs: 12, sm: 24, md: 24, lg: 24, xl: 24 }}
                >
                  <Col xl={12} lg={24} md={24} sm={24} xs={24} key={index}>
                    <ProCard
                      size="small"
                      style={{ textAlign: 'right' }}
                    >
                      <List<any>
                        dataSource={item.data}
                        rowKey={item.data.org}
                        className="hide-scrollbar"
                        style={{
                          width: '100%',
                          overflow: 'auto', // 启用滚动条
                          maxHeight: '60vh',
                        }}
                        renderItem={(i, index) => renderRank(i, index, item.title)}
                      ></List>
                    </ProCard>
                  </Col>
                </ProCard >
              </>)}
            </ProCard.TabPane>
          ))}
      </ProCard>

      <br />
    </>
  );
};

export default RankModule;
